import { defineConfig, loadEnv } from 'vite';
import path from 'path';
import { createProxy } from './build/vite/proxy';
import { wrapperEnv } from './build/utils';
import { generateModifyVars } from './build/generate/generateModifyVars';
import { createVitePlugins } from './build/vite/plugin';
/**css加上前缀 */
import postcssPresetEnv from 'postcss-preset-env';
/** 当前执行node命令时文件夹的地址（工作目录) */
const root = process.cwd();
/** 路径查找 */
const pathResolve = dir => {
	return path.resolve(__dirname, '.', dir);
};

export default defineConfig(config => {
	const { command, mode } = config;
	const isBuild = command === 'build';
	const env = loadEnv(mode, process.cwd());
	const viteEnv = wrapperEnv(env);
	const { VITE_PUBLIC_PATH, VITE_PROXY, VITE_PORT, VITE_DEL_CONSOLE } = viteEnv;

	return {
		root,
		base: VITE_PUBLIC_PATH,
		mode: mode,
		define: {
			__APPNAME__: JSON.stringify('低代码平台')
		},
		publicDir: 'public',
		cacheDir: 'node_modules/.vite',
		plugins: createVitePlugins(viteEnv, isBuild),
		resolve: {
			alias: {
				'@': pathResolve('src'),
				'@api': pathResolve('src/api')
			},
			mainFields: ['module', 'jsnext:main', 'jsnext'],
			extensions: ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json']
		},
		css: {
			postcss: {
				plugins: [postcssPresetEnv()]
			},
			preprocessorOptions: {
				//less预处理
				less: {
					modifyVars: generateModifyVars(),
					javascriptEnabled: true
				}
				//scss预处理
				// scss: {
				//   additionalData: '@import "@/assets/styles/variables.module.scss";'
				// }
			}
		},
		envDir: root,
		envPrefix: 'VITE_',
		server: {
			host: '0.0.0.0',
			port: VITE_PORT,
			strictPort: false,
			open: true,
			cors: true,
			hmr: true,
			proxy: createProxy(VITE_PROXY)
		},
		build: {
			target: ['es2020', 'edge88', 'firefox78', 'chrome87', 'safari14'],
			cssTarget: 'chrome61', // 以防止vite将rgba()颜色转化为#RGBA十六进制符号的形式。

			outDir: 'dist',
			assetsDir: 'assets',
			assetsInlineLimit: 1024 * 4, // 4k
			sourcemap: !isBuild,
			terserOptions: {
				compress: {
					keep_infinity: true,
					// 用于删除生产环境中的console
					drop_console: VITE_DEL_CONSOLE
				}
			},
			// 消除打包大小超过500kb警告
			chunkSizeWarningLimit: 500,
			rollupOptions: {
				input: {
					index: pathResolve('index.html')
				},
				// 静态资源分类打包
				output: {
					chunkFileNames: 'assets/js/[name]-[hash].js',
					entryFileNames: 'assets/js/entry-[name]-[hash].js',
					assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
				}
			}
		},
		optimizeDeps: {
			force: false
		}
	};
});
